<template>
  <BasicDrawer v-bind="$attrs" @register="register" :title="displayModuleTitle" width="90%">
    <BasicTable
      @register="registerTable"
      :data-source="executeRecordList"
      title="任务执行记录"
      size="small"
      :pagination="false"
      :scroll="{ x: false, y: 'calc(100vh - 310px)' }"
    >
      <template #toolbar>
        <a-button
          @click="onAddExecuteRecordButtonClick"
          v-if="(mode == 'todolistExecute' || mode == 'alllistExecute') && hasOperate"
          type="primary"
          ><PlusOutlined />新增执行记录</a-button
        >
        <a-radio-group
          v-model:value="typeChoose"
          button-style="solid"
          v-show="itemRecord.planfrequencytype != 0"
        >
          <a-radio-button value="all">
            <a-tooltip>
              <template #title>查看前后周期执行记录请点击本按钮。</template>
              全部周期
            </a-tooltip></a-radio-button
          >
          <a-radio-button value="current">当前周期</a-radio-button>
        </a-radio-group>
      </template>
      <template #itemname="{ record }">
        <span @click="onExecuteRecordInfoViewButtonClick(record)">
          {{ record.item?.itemname }}</span
        >
      </template>
      <template #unitname="{ record }">
        {{ record.unitname
        }}{{
          record.hazardname || record.facilityname
            ? '(' + (record.hazardname ?? '') + (record.facilityname ?? '') + ')'
            : ''
        }}
      </template>
      <template #status="{ record }">
        <a-tag v-if="record.hasconfirm === true" color="green">已确认</a-tag>
        <a-tag v-else-if="record.hasexec === false" color="red">未完成</a-tag>
        <a-tag v-else-if="record.hasexec === true" color="yellow">已完成</a-tag>

        <a-tag
          style="margin-left: 5px"
          v-if="record.hasexec === true && record.isnormal === true"
          color="green"
          >正常</a-tag
        >
        <a-tag
          style="margin-left: 5px"
          v-if="record.hasexec === true && record.isnormal === false"
          color="red"
          >异常</a-tag
        >
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              tooltip: '修改',
              icon: 'ant-design:edit-outlined',
              ifShow:
                (mode == 'todolistExecute' || mode == 'alllistExecute') &&
                hasOperate &&
                record.hasconfirm === false,
              onClick: onEditExecuteRecordButtonClick.bind(null, record),
            },
            {
              tooltip: '删除',
              icon: 'ant-design:delete-outlined',
              color: 'error',
              ifShow:
                (mode == 'todolistExecute' || mode == 'alllistExecute') &&
                hasOperate &&
                record.hasconfirm === false,
              popConfirm: {
                title: '是否确认删除',
                placement: 'topLeft',
                confirm: onDeleteExecuteRecordButtonClick.bind(null, record),
              },
            },
            {
              icon: 'ant-design:check-outlined',
              color: 'success',
              ifShow:
                (mode == 'todolistConfirm' || mode == 'alllistConfirm') &&
                record.hasexec === true &&
                record.hasconfirm === false,
              tooltip: '确认执行记录',
              onClick: onConfirmExecuteButtonClick.bind(null, record),
            },
          ]"
        />
      </template>
    </BasicTable>
    <ConfirmExecuteDrawer @register="registerConfirmExecuteDrawer" @success="opSuccess" />
    <AddOrUpdateExecuteRecord
      :orgcode="orgcode"
      @register="registerAddOrUpdateExecuteRecordModal"
      @success="opSuccess"
    />
    <ExecuteRecordInfoView @register="registerExecuteRecordInfoViewModal" @success="opSuccess" />
  </BasicDrawer>
</template>

<script lang="ts">
  import { defineComponent, ref, unref, computed, watch } from 'vue';
  import { BasicDrawer, useDrawerInner, useDrawer } from '/@/components/Drawer';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { displayTitle } from '/@/utils/QcUnifyUtil';
  import { getTaskItemExecutes, getTaskGroupExecutes } from '/@/api/ehs/taskExecute';
  import { executeRecordListColumns } from './taskBench.data';
  import ConfirmExecuteDrawer from '../taskConsole/ConfirmExecuteDrawer.vue';
  import { useModal } from '/@/components/Modal';
  import {
    deleteExecuteRecord,
    updateExecuteRecord,
    addExecuteRecord,
  } from '/@/api/ehs/taskExecute';
  import AddOrUpdateExecuteRecord from './AddOrUpdateExecuteRecord.vue';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import ExecuteRecordInfoView from './ExecuteRecordInfoView.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage } = useMessage();
  export default defineComponent({
    components: {
      BasicDrawer,
      BasicTable,
      TableAction,
      ConfirmExecuteDrawer,
      AddOrUpdateExecuteRecord,
      PlusOutlined,
      ExecuteRecordInfoView,
    },
    props: ['mode', 'orgcode'],
    setup(props, { emit }) {
      const itemid = ref('');
      const groupid = ref('');
      const orgcode = ref(props.orgcode);
      const executeRecordList = ref([]);
      const itemRecord = ref({});
      const typeChoose = ref('current');
      const hasOperate = ref(false); // 是否有增删查改执行记录的操作权限,根据这个任务项的isfinish和isend来判断
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();
      const [
        registerAddOrUpdateExecuteRecordModal,
        { openModal: openAddOrUpdateExecuteRecordModal },
      ] = useModal();
      const [registerConfirmExecuteDrawer, { openDrawer: openConfirmExecuteDrawer }] = useDrawer();
      const [registerExecuteRecordInfoViewModal, { openModal: openExecuteRecordInfoViewModal }] =
        useModal();
      const [registerTable, { setLoading }] = useTable({
        columns: executeRecordListColumns,
        canResize: true,
        showTableSetting: true,
        tableSetting: {
          redo: false,
        },
        immediate: false,
        beforeFetch: (params) => {
          if (typeChoose.value == 'all') {
            params = groupid.value;
          } else {
            params = itemid.value;
          }
          return params;
        },
        striped: false,
        showIndexColumn: false,
        showTableSetting: true,
        isTreeTable: true,
        bordered: true,
        ellipsis: true,
        indentSize: 30,
        actionColumn: {
          width: 120,
          title: '操作',
          show:
            hasOperate.value || props.mode == 'todolistConfirm' || props.mode == 'alllistConfirm',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
      });
      const [register, { closeDrawer }] = useDrawerInner((data) => {
        if (data != undefined && data != null) {
          let unrefData = unref(data);
          qcUnifyProps.value = unrefData;
          orgcode.value = props.orgcode;
          itemid.value = data.itemid;
          groupid.value = data.groupid;
          hasOperate.value = data.hasOperate;
          itemRecord.value = data.itemRecord;
          typeChoose.value = 'current';
          getExecuteRecordList();
        }
      });

      /**
       * 删除执行记录
       */
      function onDeleteExecuteRecordButtonClick(record) {
        deleteExecuteRecord(record.execid).then((res) => {
          if (!res) {
            createMessage.success('删除成功');
            opSuccess();
          } else {
            createMessage.error('删除失败');
          }
        });
      }

      /**
       * 确认执行记录
       */
      function onConfirmExecuteButtonClick(record) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '任务执行记录',
          operateString: '确认',
          dataId: record.execid,
        };
        openConfirmExecuteDrawer(true, propsData);
      }

      /**
       *  新增执行记录(填写执行记录)
       */
      function onAddExecuteRecordButtonClick() {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '任务执行记录',
          operateType: OperationTypeEnum.ADD,
          taskItemRecord: itemRecord.value,
        };
        openAddOrUpdateExecuteRecordModal(true, propsData);
      }

      /**
       * 编辑执行记录
       */
      function onEditExecuteRecordButtonClick(record) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '任务执行记录',
          operateType: OperationTypeEnum.EDIT,
          taskItemRecord: itemRecord.value,
          dataId: record.execid,
        };
        openAddOrUpdateExecuteRecordModal(true, propsData);
      }

      /**
       * 查看指定执行记录
       */
      function onExecuteRecordInfoViewButtonClick(record) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '任务执行记录',
          operateType: OperationTypeEnum.VIEW,
          dataId: record.execid,
        };
        openExecuteRecordInfoViewModal(true, propsData);
      }

      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });

      function getExecuteRecordList() {
        if (typeChoose.value == 'all') {
          getTaskGroupExecutes(groupid.value).then((res) => {
            executeRecordList.value = res ?? [];
          });
        } else {
          getTaskItemExecutes(itemid.value).then((res) => {
            executeRecordList.value = res ?? [];
          });
        }
      }

      watch(
        () => typeChoose.value,
        (newVal, oldVal) => {
          getExecuteRecordList();
        },
      );

      function opSuccess() {
        getExecuteRecordList();
      }

      return {
        orgcode,
        hasOperate,
        itemRecord,
        register,
        registerTable,
        registerExecuteRecordInfoViewModal,
        registerConfirmExecuteDrawer,
        registerAddOrUpdateExecuteRecordModal,
        displayModuleTitle,
        qcUnifyProps,
        typeChoose,
        executeRecordList,
        opSuccess,
        onDeleteExecuteRecordButtonClick,
        onConfirmExecuteButtonClick,
        onAddExecuteRecordButtonClick,
        onEditExecuteRecordButtonClick,
        onExecuteRecordInfoViewButtonClick,
      };
    },
  });
</script>

<style scoped></style>
